package com.ly.hotel.view.fragments.vod;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;

import com.ly.hotel.common.MyApplication;
import com.ly.hotel.model.Vodvideo;
import com.ly.hotel.msgevent.ControlVodEvent;
import com.ly.hotel.msgevent.SetVodPlayEvent;
import com.ly.hotel.adaptor.HardwareInterface;
import com.ly.hotel.service.SPABackService;
import com.ly.hotel.view.common.BaseActivity;

import android.content.Intent;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.ly.hotel.R;

import de.greenrobot.event.EventBus;

/**
 * Base Activity，原生MediaPlayer视频播放器页面基类。 如果要实现自定义UI的视频播放器页面，只需要继承该类，在此基础上实现一个
 * {@link NativeMediaController.MediaControllerGenerator}接口即可。
 * 
 * Created by Anchorer on 2014/9/23.
 */
public class BaseNativeVideoPlayerActivity extends BaseActivity implements SurfaceHolder.Callback,
		MediaPlayer.OnPreparedListener, NativeMediaController.MediaPlayerControl,
		NativeMediaController.MediaControllerGenerator {

	private SurfaceView videoSurface;
	protected MediaPlayer mPlayer;
	protected NativeMediaController mController;
	protected Intent mIntent;
	private SurfaceHolder mVideoHolder;
	private int mCurrentPosition;
	public String filmName;
	public String filmArea;
	public int filmId;
	public Integer position;
	public String nextVodsList;
	private ThisHandler handlerMsg = new ThisHandler(this);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.video_native_activity);
		mIntent = getIntent();
		filmName = mIntent.getStringExtra("filmName");
		filmArea = mIntent.getStringExtra("filmArea");
		filmId = mIntent.getIntExtra("filmId", -1);
		position  = mIntent.getIntExtra("position", 0);
		nextVodsList   = mIntent.getStringExtra("nextVodsList");
		Log.i("vod", "初始播放列表->" + nextVodsList);
		mCurrentPosition = 0;
		videoSurface = (SurfaceView) findViewById(R.id.video_surface);
		mVideoHolder = videoSurface.getHolder();
		mVideoHolder.addCallback(this);

		mController = new NativeMediaController(this);
		mController.setUIGenerator(this);
		
		this.className = this.getClass().getName();

	}

	@Override
	public BaseMediaControllerHolder generateMediaController() {
		return new BaseMediaControllerHolder();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		mController.show();
		return false;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Log.i("medio", "BaseNativeVideoPlayerActivity OnKeyDown");
		if (mController.myOnKeyDown(keyCode, event) == false)
			return super.onKeyDown(keyCode, event);
		return true;
	}

	// Implement SurfaceHolder.Callback
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Log.i("medio", "surface created init");
		try {
			// 创建一个MediaPlayer对象
			if(mPlayer == null)
				mPlayer = new MediaPlayer();
			
			if (mPlayer.isPlaying())  
	        {  
				mPlayer.stop();  
				mPlayer.release();  
				mPlayer = null;  
				mPlayer = new MediaPlayer(); 
	        }
			// 设置播放的视频数据源
			mPlayer.setDataSource(this, Uri.parse(mIntent.getStringExtra("path")));

			// 设置AudioStreamType
			mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			// 将视频输出到SurfaceView
			mPlayer.setDisplay(mVideoHolder);
			// 播放准备，使用异步方式，配合OnPreparedListener
			mPlayer.prepareAsync();
			// 设置相关的监听器
			mPlayer.setOnPreparedListener(this);
			mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

				@Override
				public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
					Log.e("medio", "onError");
					return false;
				}
			});
			mPlayer.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer arg0) {
					Log.e("vod", "onCompletion");
					if(filmId >= 0){
						EventBus.getDefault().post(new SetVodPlayEvent(filmId, SetVodPlayEvent.END));
					}
					
					if (MyApplication.isLoopPlay) {
						mPlayer.reset();
						try {
							mPlayer.setDataSource(BaseNativeVideoPlayerActivity.this,
									Uri.parse(mIntent.getStringExtra("path")));
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						} catch (SecurityException e) {
							e.printStackTrace();
						} catch (IllegalStateException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
						mPlayer.prepareAsync();
					} else /*if(nextVodsList != null)*/{
						if(!handlerMsg.hasMessages(0)){
							handlerMsg.sendEmptyMessageDelayed(0, 2000);
						}
					}/*else {
						finish();
					}*/
				}
			});
			mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

		} catch (IllegalArgumentException e) {
			Log.e("medio", "IllegalArgumentException:" + e.getMessage());
			e.printStackTrace();
		} catch (SecurityException e) {
			Log.e("medio", "SecurityException:" + e.getMessage());
			e.printStackTrace();
		} catch (IllegalStateException e) {
			Log.e("medio", "IllegalStateException:" + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("medio", "IOException:" + e.getMessage());
			e.printStackTrace();
		}
		Log.i("medio", "surface created.");
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
	}

	// Implement VideoMediaCController.MediaPlayerControl
	@Override
	public void start() {
		try {
			if (mPlayer != null)
				mPlayer.start();
		} catch (Exception e) {
			Log.e("medio", "start " + e.getMessage());
		}
	}

	@Override
	public void pause() {
		try {
			if (mPlayer != null)
				mPlayer.pause();
		} catch (Exception e) {
			Log.e("medio", "pause " + e.getMessage());
		}
	}

	@Override
	public int getDuration() {
		try {
			if (mPlayer != null) {
				return mPlayer.getDuration();
			} else
				return 0;
		} catch (Exception e) {
			Log.e("medio", "getDuration " + e.getMessage());
			return 0;
		}
	}

	@Override
	public int getCurrentPosition() {
		try {
			if (mPlayer != null) {
				return mPlayer.getCurrentPosition();
			} else
				return 0;
		} catch (Exception e) {
			Log.e("medio", "getCurrentPosition " + e.getMessage());
			return 0;
		}
	}

	@Override
	public void seekTo(int pos) {
		try {
			if (mPlayer != null) {
				mPlayer.seekTo(pos);
			}
		} catch (Exception e) {
			Log.e("medio", "seekTo " + e.getMessage());
		}
	}

	@Override
	public boolean isPlaying() {
		return mPlayer != null && mPlayer.isPlaying();
	}

	@Override
	public int getBufferPercentage() {
		return 0;
	}

	@Override
	public boolean canPause() {
		return true;
	}

	@Override
	public boolean canSeekBackward() {
		return true;
	}

	@Override
	public boolean canSeekForward() {
		return true;
	}

	@Override
	public boolean isFullScreen() {
		return false;
	}

	@Override
	public void toggleFullScreen() {
	}

	// End Implement VideoMediaCController.MediaPlayerControl

	// Implement MediaPlayer.OnPreparedListener
	@Override
	public void onPrepared(MediaPlayer mp) {
		Log.e("vod", "onPrepared ,mCurrentPosition=" + mCurrentPosition);
		try {
			mPlayer.start();
			 
			if(mCurrentPosition == 0){
				mController.setMediaPlayer(this);
				mController.setAnchorView((FrameLayout) findViewById(R.id.video_surface_container));
				mController.show();
				mController.updatePausePlay();
				if(position != 0){
					this.seekTo(position);
					mCurrentPosition = position;
				}
			}
			this.seekTo(mCurrentPosition);
			
//			if(filmId >= 0 && mCurrentPosition == 0){
				Log.i("vod", "开始播放电影");
//				EventBus.getDefault().post(new SetVodPlayEvent(filmId, SetVodPlayEvent.START));
//				EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_VOD_PREFIX + "首次播放" + "\t" + filmArea + "\t" + filmName));
//			}
			
			HardwareInterface.setMuteFlag(false);

		} catch (Exception e) {
			Log.e("vod", "onPrepared " + e.getMessage());
		}
	}

	// End MediaPlayer.OnPreparedListener

	@Override
	protected void onPause() {
		Log.i("vod", "onPause");
		HardwareInterface.setMuteFlag(true);
//		pause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		Log.i("vod", "onResume");
		HardwareInterface.setMuteFlag(false);
		super.onResume();
	
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (mPlayer != null)
			mPlayer.start();
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mPlayer != null){
			Log.i("vod", "mPlayer.pause()");
			mPlayer.pause();
			mCurrentPosition = this.getCurrentPosition();
		}
	}
/*
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("videoPosition", mCurrentPosition);
	}
*/
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i("vod", "片长=" + mPlayer.getDuration() + ",当前位置=" + mCurrentPosition);
		if(filmId >= 0){
			for(Vodvideo vv : app.vodHistory){
				if(vv.getId().equals(filmId)){
					if(mPlayer.getDuration() - mCurrentPosition <= 5 * 60 * 1000){
						vv.setPlayPosition(0);
					} else {
						vv.setPlayPosition(mCurrentPosition);
					}
					break;
				}
			}
			
			if(mPlayer.getDuration() - mCurrentPosition <= 5 * 60 * 1000){
				//web接口用的，使用web接口不会有本地的数据源，所以保存是失败的，需要换一种方法
				if(app.mySpaceIsKey("film" + filmId).equals("true")){
					app.mySpaceDelKey("film" + filmId);
				}
				app.mySpacePutValue("film" + filmId, "" + 0);
				Log.i("vod", "1.记录当前位置=" + app.mySpaceGetValue("film" + filmId));
			} else {
				if(app.mySpaceIsKey("film" + filmId).equals("true")){
					app.mySpaceDelKey("film" + filmId);
				}
				app.mySpacePutValue("film" + filmId, "" + mCurrentPosition);
				Log.i("vod", "2.记录当前位置=" + app.mySpaceGetValue("film" + filmId));
			}
			
			EventBus.getDefault().post(new SetVodPlayEvent(filmId, SetVodPlayEvent.END));
		}
		//释放之
		releaseMediaPlayer();
	}

	private void releaseMediaPlayer() {
		try {
			if (mPlayer != null) {
				mPlayer.stop();
				mPlayer.reset();
				mPlayer.release();
				mPlayer = null;
			}
		} catch (Exception e) {
			Log.e("medio", "releaseMediaPlayer " + e.getMessage());
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	public void onEventMainThread(ControlVodEvent event) {

		if (event.getType() == ControlVodEvent.VOD_START) {
			start();
		} else if (event.getType() == ControlVodEvent.VOD_STOP) {
			pause();
		} else if (event.getType() == ControlVodEvent.VOD_SEEK) {
			if(event.getSeektoPosition() != -1){
				if(mPlayer != null){
					int len = mPlayer.getDuration();
					
					this.seekTo((len/1000) * event.getSeektoPosition());
					mCurrentPosition = (len/1000) * event.getSeektoPosition();
				}
			}
		}
	}
	
	private static class ThisHandler extends Handler {
		private WeakReference<BaseNativeVideoPlayerActivity> wrActivity;
		
		public ThisHandler(BaseNativeVideoPlayerActivity activity) {
			wrActivity = new WeakReference<BaseNativeVideoPlayerActivity>(activity);
		}
		
		@Override
		public void handleMessage(Message message) {
			BaseNativeVideoPlayerActivity act = wrActivity.get();
			if (act != null) {
				if(message.what == 0){
					Integer tegId = new Integer(act.filmId);
						try {
							Vodvideo nextVod = SPABackService.getVideoById(tegId);
							if(nextVod != null){
								String tmp[] =  MyApplication.getHostIp().split(":");
								String url = nextVod.getPath();
								try {
									//由于空格转码后为+号，所以替换+号成%20,"/"不需要转码所以还原
									url = URLEncoder.encode(url, "utf-8").replaceAll("\\+","%20").replaceAll("%2F","/");
								} catch (UnsupportedEncodingException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

								act.filmName = nextVod.getName();
								act.filmId = nextVod.getId().intValue();


								if(tmp.length == 2 && !nextVod.getServerPort().equals("0")){
									url = "http://" + tmp[0] + ":" + nextVod.getServerPort() + "/" + url;
								}else{
									url = MyApplication.getHostResUrl() + url;
								}
								act.mPlayer.stop();
								act.mPlayer.reset();
								act.mPlayer.setDataSource(act, Uri.parse(url));
								act.mPlayer.prepareAsync();
							}else {
								act.finish();
							}
						} catch (NumberFormatException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalArgumentException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SecurityException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				}
			}
		}
	}
}
